package com.feijia.aijingjingus;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.feijia.aijingjingus.util.PreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import cn.sharesdk.onekeyshare.OnekeyShare;

import static com.feijia.aijingjingus.GlobalHelper.DetectionDatetime;
import static com.feijia.aijingjingus.GlobalHelper.DetectionResults;
import static com.feijia.aijingjingus.GlobalHelper.DetectionType;
import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.RawDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.Report;
import static com.feijia.aijingjingus.GlobalHelper.SelectDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.ShowLocalDetection;
import static com.feijia.aijingjingus.GlobalHelper.isNetOut;
import static com.feijia.aijingjingus.GlobalHelper.tip;


public class DetectionResultActivity extends AppCompatActivity {
    private JSONObject detectionData;
    private TextView txtRawData, txtDetectionResults, txtReport, txtTips, txtLocal;
    private RelativeLayout rlMain, rlLoading,rl_DetectionResults;
    OptionsPickerView pvNetOut;
    Handler handler = new Handler();
    Context context = this;


    final Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            try {
                if (detectionData.getString("type").equals("HCG")) {
                    if(detectionData.getDouble("RawDetectionData")>0) {
//                        txtRawData.setText(detectionData.getInt("RawDetectionData") + " IU/L");
                    }

                    /*
                    if (detectionData.getInt("DetectionResults") != 0) {
                        txtDetectionResults.setText(getString(R.string.Congratulation));
                        //txtDetectionResults.setText(String.format(context.getString(R.string.Pregnanted_more_str), detectionData.getInt("DetectionResults")));
                    }
                    else
                        txtDetectionResults.setText(context.getString(R.string.NotPregnanted_more_str));
                    */
                    txtDetectionResults.setText(String.format(detectionData.getString("DetectionResults")));
//                    findViewById(R.id.button20).setVisibility(View.GONE);
                } else if (detectionData.getString("type").equals("LH")) {
//                    txtRawData.setText(detectionData.getInt("RawDetectionData") + " IU/L");
                    txtDetectionResults.setText(String.format(context.getString(R.string.Ovulation_more_str), detectionData.getInt("DetectionResults")));
                    /*
                    if (detectionData.getInt("DetectionResults") <= 72) {
                        txtDetectionResults.setText(String.format(context.getString(R.string.Ovulation_near)));
                    }
                    if (detectionData.getInt("DetectionResults") > 72) {
                        txtDetectionResults.setText(String.format(context.getString(R.string.Ovulation_far)));
                    }
                    */
                    /*
                    if (detectionData.getInt("DetectionResults") == 0) {
                        txtDetectionResults.setText(String.format(context.getString(R.string.Negative)));
                    }
                    if (detectionData.getInt("DetectionResults") > 0) {
                        txtDetectionResults.setText(String.format(context.getString(R.string.Positive)));
                    }
                    */
                    txtDetectionResults.setText(String.format(detectionData.getString("DetectionResults")));
//                    findViewById(R.id.button17).setVisibility(View.GONE);
                }

                txtReport.setText(detectionData.getString("Report"));
                txtTips.setText(detectionData.getString("tip"));
//                txtLocal.setText(detectionData.getString("DetectionLocation"));
                rlMain.setVisibility(View.VISIBLE);
                rlLoading.setVisibility(View.INVISIBLE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detection_result);

        //      性别男时修改UI背景色
//        if(PreferencesUtils.getString(getApplicationContext(),PreferencesUtils.PREFERENCE_NAME).equals("男")){
//            rl_DetectionResults=(RelativeLayout)findViewById(R.id.rl_DetectionResults);
//            rl_DetectionResults.setBackground(getDrawable(R.drawable.resultbgman));
//            RelativeLayout rl_top=(RelativeLayout)findViewById(R.id.relativeLayout);
//            rl_top.setBackground(getDrawable(R.drawable.top_bar_with_shadow_two));
//            Button button=(Button)findViewById(R.id.imageButton);
//            button.setBackground(getDrawable(R.drawable.ripple_red_rectangle_with_shadow_two));
//
//        }

        //DetectionLocation="San Diago";
        if (GUserNum.equals(""))
            findViewById(R.id.linearLayout3).setVisibility(View.GONE);
//        txtRawData = (TextView) findViewById(R.id.txtRawData);
        txtDetectionResults = (TextView) findViewById(R.id.txtDetectionResults);
        txtReport = (TextView) findViewById(R.id.txtReport);
        txtTips = (TextView) findViewById(R.id.txtTips);
//        txtLocal = (TextView) findViewById(R.id.txtLocal);
        rlMain = (RelativeLayout) findViewById(R.id.rlDetectionResult);
        rlLoading = (RelativeLayout) findViewById(R.id.rlDetectionResultLoading);
        if (ShowLocalDetection) {
            if (!DetectionResults.isEmpty()) {
                if (DetectionType.equals("HCG")) {
                    /*
                    txtRawData.setText(RawDetectionData + " mIU/L");
                    if (Integer.parseInt(DetectionResults) != 0) {
                        txtDetectionResults.setText(getString(R.string.Congratulation));
                        //txtDetectionResults.setText(String.format(context.getString(R.string.Pregnanted_more_str), Integer.parseInt(DetectionResults)));
                    }
                    else
                        txtDetectionResults.setText(context.getString(R.string.NotPregnanted_more_str));
                    */
                    if(Double.parseDouble(RawDetectionData)>0) {
//                        txtRawData.setText(RawDetectionData + " IU/L");
                    }
                    txtDetectionResults.setText(String.format(DetectionResults));
//                    findViewById(R.id.button20).setVisibility(View.GONE);
                } else if (DetectionType.equals("LH")) {
                    //txtRawData.setText(RawDetectionData + " mIU/L");
                    //txtDetectionResults.setText(String.format(context.getString(R.string.Ovulation_more_str), Integer.parseInt(DetectionResults)));
                    /*
                    if (Integer.parseInt(DetectionResults) <= 72) {
                        txtDetectionResults.setText(context.getString(R.string.Ovulation_near));
                    }
                    if (Integer.parseInt(DetectionResults) > 72) {
                        txtDetectionResults.setText(context.getString(R.string.Ovulation_far));
                    }*/
                    /*
                    if (Integer.parseInt(DetectionResults) == 0) {
                        txtDetectionResults.setText(String.format(context.getString(R.string.Negative)));
                    }
                    if (Integer.parseInt(DetectionResults) > 0) {
                        txtDetectionResults.setText(String.format(context.getString(R.string.Positive)));
                    }
                    */
//                    findViewById(R.id.button17).setVisibility(View.GONE);
                    /*if(Double.parseDouble(RawDetectionData)>0) {
                        txtRawData.setText(RawDetectionData + " IU/L");
                    }*/
                    txtDetectionResults.setText(String.format(DetectionResults));
                }
                txtReport.setText(Report);
                txtTips.setText(tip);
//                txtLocal.setText(DetectionLocation);
                rlMain.setVisibility(View.VISIBLE);
                rlLoading.setVisibility(View.INVISIBLE);
            } else {
                Toast.makeText(getApplicationContext(), context.getString(R.string.networkConnectionFailed),
                        Toast.LENGTH_SHORT).show();
            }
        } else if(isNetOut) {
            pvNetOut = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    //String tx = cardItem.get(options1).getPickerViewText();
                    //btn_CustomOptions.setText(tx);
                }
            })
                    .setLayoutRes(R.layout.pickerview_custom_net_out_options, new CustomListener() {
                        @Override
                        public void customLayout(View v) {
                            final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                            ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                            final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                            tvSubmit.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    pvNetOut.returnData();
                                    pvNetOut.dismiss();
                                    Intent intent =new Intent("controlCenterActivity");
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent);
                                }
                            });
                            ivCancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //pvNetOut.dismiss();
                                }
                            });
                        }
                    })
                    .isDialog(true)
                    .setOutSideCancelable(false)
                    .build();
            pvNetOut.setPicker(new ArrayList<>());//添加数据
            handler.post(new Runnable() {
                @Override
                public void run() {
                    pvNetOut.show();
                }
            });
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject root = new JSONObject();
                    try {
                        root.put("UserNo", Long.parseLong(GUserNum) /*Long.parseLong(GUserNum)*/);
                        root.put("DetectionDateStart", DetectionDatetime.substring(0, 10));
                        root.put("DetectionDateEnd", DetectionDatetime.substring(0, 10));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/getDetections.php");
                    System.out.println(out);
                    detectionData = SelectDetectionData(out, DetectionDatetime.substring(11));
                    System.out.println(detectionData);
                    handler.post(runnableUi);
                }
            }).start();
        }
        TextView dateTextView = (TextView) findViewById(R.id.textView5);
        dateTextView.setText(DetectionDatetime);
    }

    public void onClickConctrolCenter(View view) {
        Intent intent = new Intent("controlCenterActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    public void onClickDetection(View view) {
        Intent intent = new Intent("controlCenterActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    public void onClickUser(View view) {
        Intent intent = new Intent("ImprovePersonalInformationActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickDetectionHistory(View view) {
        Intent intent = new Intent("detectionHistoryActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickBack(View view) {
        if (GUserNum.equals("")) {
            findViewById(R.id.EscRelativeLayout).setVisibility(View.VISIBLE);
        } else {
            Intent intent = new Intent("controlCenterActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
    }

    public void onClickLoginYes(View view) {
        Intent intent = new Intent("MainActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickLoginNo(View view) {
        Intent intent = new Intent("controlCenterActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && GUserNum.equals("")) {
            findViewById(R.id.EscRelativeLayout).setVisibility(View.VISIBLE);
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (ShowLocalDetection) {
                Intent intent = new Intent("controlCenterActivity");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            } else {
                finish();
            }

        }
        return false;
    }

    public void onClickShare(View view) {
        showShare();
    }

    private void showShare() {
        try {
            saveCurrentImage();
        } catch (IOException e) {
            e.printStackTrace();
        }
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权

        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle(getString(R.string.app_name));
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl("http://aaaaahealth.com/");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(getString(R.string.ShareText));
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        //oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath(Environment.getExternalStorageDirectory().toString() + "/w65/share_bitmap/myshare.png");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://aaaaahealth.com/");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(getString(R.string.ShareComment));
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("ShareSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://aaaaahealth.com/");
// 启动分享GUI
        oks.show(this);
    }

    private void saveCurrentImage() throws IOException {
        //获取当前屏幕的大小
        int width = getWindow().getDecorView().getRootView().getWidth();
        int height = getWindow().getDecorView().getRootView().getHeight();
        //生成相同大小的图片
        Bitmap temBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //找到当前页面的跟布局
        View view = getWindow().getDecorView().getRootView();
        //设置缓存
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        //从缓存中获取当前屏幕的图片
        temBitmap = view.getDrawingCache();

        //输出到sd卡
        String path = Environment.getExternalStorageDirectory().toString() + "/w65/share_bitmap/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File myIconFile = new File(path + "myshare.png");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myIconFile));
        temBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }
}
